package com.clouddot.baipai.ui.service;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.clouddot.baipai.model.beam.FTPTip;
import com.clouddot.baipai.ui.activity.A_LaunchActivity;
import com.clouddot.baipai.ui.util.Ftp.FTPUtil;
import com.clouddot.baipai.ui.util.MyLog;
import com.clouddot.baipai.ui.util.ToastUtil;
import com.clouddot.baipai.model.beam.getVersionInfo.XMLBean;

import java.io.File;
import java.io.IOException;


public class MyService extends Service {
    public static Thread thread;  //监听自动更新
    public static Thread thread1; //监听退出重启软件
    public boolean isOpen;

    @Override
    public void onCreate() {
        super.onCreate();
        if(thread == null) {
            thread = new Thread() {
                @Override
                public void run() {
                    super.run();
                    while (true) {
                        try {
                            sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (Env.getAppContext() != null) {
                             if (Env.getAppContext().isAutoUpdate) {
                                try {
                                    int time = Integer.parseInt(Environment.getInstance().fileUtil.getCurrentTimeString());
                                    Log.i( "run: ",Env.getAppContext().autoUpdateTime+"");
                                    if(time == Env.getAppContext().autoUpdateTime) {

                                        final XMLBean xmlBean = Env.getFTPUtil().getVersionCode("/Banpai/version.xml");
                                        final PackageManager manager = Env.getContent().getPackageManager();
                                        int versionCode = manager.getPackageInfo(Env.getContent().getPackageName(), 0).versionCode;
                                        if (versionCode < Integer.parseInt(xmlBean.getVersion())) {
                                            Env.getAppContext().isAutoUpdate = false;
                                            handler.sendEmptyMessage(isAuto);
                                        }
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (PackageManager.NameNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            };

            thread.start();
        }

        if(thread1 == null) {
            thread1 = new Thread() {
                @Override
                public void run() {
                    super.run();

                    while (true) {
                        try {
                            sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ActivityManager activityManager = (ActivityManager) MyService.this.getSystemService(Context.ACTIVITY_SERVICE);
                        //获得最顶层的Activity
                        ComponentName componentName = activityManager.getRunningTasks(1).get(0).topActivity;

                        Log.e("", "getActivityTop: " + componentName.getPackageName());
                        Log.e("", "getActivityTop: " + componentName.getClassName());
                        if (Env.getAppContext() != null) {
                            if(Env.getAppContext().isOpenService) {
                                if (!componentName.getPackageName().equals("com.clouddot.baipai")) {
                                    Intent i = new Intent(MyService.this, A_LaunchActivity.class);
                                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    MyService.this.startActivity(i);
                                }
                            }
                        }else{
                            Intent i = new Intent(MyService.this, A_LaunchActivity.class);
                            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            MyService.this.startActivity(i);
                        }
                    }

                }
            };
            thread1.start();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     *
     * 升级安装包
     */
    private void startUpdate(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Message message = new Message();
                    message.obj = "开始下载升级包";
                    message.what = 2;
                    handler.sendMessage(message);
                    Env.getFTPUtil().downloadSingleFile(Env.getAppContext().upateUrl, "/mnt/sdcard",
                            "banpai.apk", new FTPUtil.DownLoadProgressListener() {
                                @Override
                                public void onDownLoadProgress(String currentStep, final long downProcess, File file) {
                                    if (currentStep.equals(FTPTip.FTP_DOWN_SUCCESS)) {
                                        Intent install = new Intent();
                                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        install.setAction(Intent.ACTION_VIEW);
                                        install.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/banpai.apk")),
                                                "application/vnd.android.package-archive");
                                        // 这里的是你下载好的文件路径
                                        Env.getContent().startActivity(install);
                                        Env.info("-----downUpdateFile--successful");
                                    } else if (currentStep.equals(FTPTip.FTP_DOWN_LOADING)) {
                                        Env.info("-----downUpdateFile---" + downProcess + "%");
                                        Message message = new Message();
                                        message.obj = "已经下载 " + downProcess + " %";
                                        message.what = 2;
                                        handler.sendMessage(message);
                                    }
                                }
                            });
                } catch (Exception e) {
                    Env.error(Environment.getInstance().fileUtil.Errorinfo(e));

                    Env.getAppContext().isAutoUpdate = true;
                }
            }
        }).start();

    }

    private static final int isAuto  = 1;
    /**
     *
     * 结束获取信息的handle机制
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case isAuto:
                    startUpdate();
                    break;
                case 2:
                    ToastUtil.showToast(Env.getContent(),msg.obj.toString());
                    break;
                default:
                    break;
            }
        }
    };




}
